﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using Atom.Core;

namespace Googler.Utilities.Web
{
    public class HttpRequestor
    {
        Stream responseStream;
        HttpWebRequest objRequest;
        HttpWebResponse objResponse;
        StreamWriter myWriter = null;
        bool isRequestOpen;
        string postedParams;
        string url;
        public void Open(string url, params string[] nameValue)
        {//open streams here        
            postedParams = GetQueryString(nameValue);
            this.url = url;
            isRequestOpen = true;
        }

        public Stream PostRequestStreem()
        {
            if (!isRequestOpen)
                throw new ApplicationException("Can't post request, the object is closed");
            try
            {
                objRequest = (HttpWebRequest)WebRequest.Create(url);
                objRequest.Method = "Post";
                objRequest.ContentLength = postedParams.Length;
                objRequest.ContentType = "application/x-www-form-urlencoded";

                myWriter = new StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(postedParams);
                myWriter.Close();
                objResponse = (HttpWebResponse)objRequest.GetResponse();
                responseStream = objResponse.GetResponseStream();

                return responseStream;
            }
            catch
            {
                Close();
                throw;
            }
        }
        public Stream GetRequestStreem(string targetLink)
        {
            if (!isRequestOpen)
                throw new ApplicationException("Can't post request, the object is closed");
            try
            {
                objRequest = (HttpWebRequest)WebRequest.Create(targetLink);
                objRequest.Method = "GET";
                objResponse = (HttpWebResponse)objRequest.GetResponse();
                responseStream = objResponse.GetResponseStream();
                return responseStream;
            }
            catch
            {
                Close();
                throw;
            }
        }

        public void Close()
        {
            if (!isRequestOpen)
                try
                {
                    responseStream.Close();
                }
                catch { }
            try
            {
                objResponse.Close();
            }
            catch { }
            isRequestOpen = false;
        }

        public string Post(string url, params string[] nameValue)
        {
             try
            {Open(url, nameValue);
            Stream rd = PostRequestStreem();
            StreamReader ms = new StreamReader(rd);
            string ret = ms.ReadToEnd();
            ms.Close();
            Close();
            return ret;
                    }
            catch { return ""; }}
        public string Get(string directLink)
        {
            try
            {
                isRequestOpen = true;
                directLink = directLink.EndsWith("&output=atom") ? directLink : directLink + "&output=atom";
                Stream rd = GetRequestStreem(directLink);
                StreamReader ms = new StreamReader(rd);
                string ret = ms.ReadToEnd();
                ms.Close();
                Close();

                return ret;
            }
            catch { return ""; }
        }
        public HttpRequestorResult Get(string url, params string[] nameValue)
        {
            Open(url, nameValue);
            Stream rd = GetRequestStreem(url + "?" + postedParams);
            StreamReader ms = new StreamReader(rd);

            string ret = ms.ReadToEnd();
            List<string> links = GetMoreLinks(ret);
            ms.Close();
            Close();

            return new HttpRequestorResult()
            {
                Response = ret,
                MoreLinks = links
            };
        }

        private List<string> GetMoreLinks(string ret)
        {
            int startFrom = ret.IndexOf("جميع المقالات البالغ عددها");
            List<string> list = new List<string>();

            while (startFrom != -1)
            {
                string link = ExtractMoreLink(ret, startFrom);
                list.Add(link);
                startFrom = ret.IndexOf("جميع المقالات البالغ عددها", startFrom + 1);
            }

            return list;
        }

        private static string ExtractMoreLink(string ret,int startFrom )
        {
            
            int httpIndex = -1;

            while (httpIndex == -1)
            {
                httpIndex = ret.IndexOf("http://", startFrom, 7);
                startFrom = startFrom - 1;
            }
            int endAt = ret.IndexOf("&quot;", httpIndex);
            string link = ret.Substring(httpIndex, endAt - httpIndex);

            return link.Replace("&amp;amp;", "&");
        }


        private static String GetQueryString(string[] nameValue)
        {
            String strPost = string.Empty;
            if (nameValue != null)
            {
                for (int i = 0; i < nameValue.Length; i += 2)
                {
                    strPost += nameValue[i] + "=" + Googler.Utilities.Mvc.MvcHelper.HttpEncode(nameValue[i + 1]) + "&";
                }
                strPost = strPost.TrimEnd('&');
            }
            System.Diagnostics.Debug.Write(strPost);
            return strPost;
        }

    }
}